package gui.view;

import gui.Activator;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import vworld.ServerSingleton;

public class ServerView extends ViewPart {
	public static final String ID = "gui.view.ServerView";
	private Button startButton;
	private Button stopButton;
	private Text port;

	public void createPartControl(Composite parent) {
		GridLayout layout = new GridLayout();
		layout.marginWidth = 0;
		layout.marginHeight = 0;
		layout.makeColumnsEqualWidth = true;
		layout.numColumns = 2;
		parent.setLayout(layout);

		new Label(parent, SWT.FLAT).setText("Port");
		port = new Text(parent, SWT.BORDER);
		port.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false,
				false));
		port.setText("900");

		startButton = new Button(parent, SWT.FLAT);
		startButton.setText("Start server");
		startButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				false, false));
		startButton.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent e) {
			}

			public void widgetSelected(SelectionEvent event) {
				try {
					ServerSingleton.getInstance().main(new String[0],
							port.getText());
					startButton.setEnabled(false);
					stopButton.setEnabled(true);
					System.out.println("Server launched");
				} catch (Exception e) {
					Status status = new Status(IStatus.ERROR,
							Activator.PLUGIN_ID, 0, e.getMessage(), null);
					ErrorDialog.openError(
							Display.getCurrent().getActiveShell(), "ERROR",
							"Error while launching server.", status);
					ServerSingleton.getInstance().orb.destroy();
					ServerSingleton.getInstance().namingService.destroy();
					System.err.println("ERROR: " + e);
					e.printStackTrace();
				}
			}
		});

		stopButton = new Button(parent, SWT.FLAT);
		stopButton.setText("Stop server");
		stopButton.setEnabled(false);
		stopButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL,
				true, true));
		stopButton.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent e) {
			}

			public void widgetSelected(SelectionEvent e) {
				startButton.setEnabled(true);
				stopButton.setEnabled(false);
				ServerSingleton.getInstance().orb.destroy();
				ServerSingleton.getInstance().namingService.destroy();
				System.out.println("Server closed");
			}
		});
	}

	public void setFocus() {
	}
}